package com.jxs.android.cmcc;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.jxs.android.cmcc.boot.SelfApplication;
import com.jxs.android.cmcc.config.CmccConfig;
import com.jxs.android.cmcc.data.MenuInfo;
import com.jxs.android.cmcc.db.InterfaceHolder;
import com.jxs.android.cmcc.db.MenuHolder;
import com.jxs.android.cmcc.db.TableHolder;
import com.jxs.android.util.StartHelper;
import com.jxs.android.util.StringUtils;
import com.jxs.android.weiget.PopMsg;
import com.jxs.android.weiget.ReportContainer;
import com.jxs.android.weiget.ReportContainer.Rate;
import com.jxs.android.weiget.TopBar;
import com.jxs.android.weiget.WheelDateDialog;

@SuppressLint({ "HandlerLeak", "SimpleDateFormat", "DefaultLocale" })
public class TableList extends TableAbstractActivity {

	private MenuInfo menuInfo;

	private String statDate;
	private ReportContainer mReport;
	private TopBar topBar;
	private List<String> titles = new ArrayList<String>();
	private int scrollingStep = 1;
	private String selectedDate;

	private final int REQ_HITCH_TIME = 0x006;
	private java.text.SimpleDateFormat sdf_show = new java.text.SimpleDateFormat("yy/MM/dd");
	private boolean isHeighted = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		int screenHeight = getWindowManager().getDefaultDisplay().getHeight(); // 屏幕高（像素，如：800p）
		if (screenHeight <= 800) {
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		} else {
			isHeighted = true;
		}
		if (null != getIntent() && null != getIntent().getExtras()) {
			menuInfo = (MenuInfo) getIntent().getExtras().getSerializable("menuInfo");
			statDate = InterfaceHolder.getValue(menuInfo.getInterface_id());
			List<MenuInfo> menuInfos = MenuHolder.getMenuInfos(menuInfo.getMenu_id(), MenuHolder.Keys.TABLE_MENU_LEVEL);
			titles.clear();
			for (MenuInfo info : menuInfos) {
				titles.add(info.getMenu_name());
			}
			int index = titles.size() - 1;
			if (index == 4) {
				scrollingStep = 1;
			} else if (index > 4) {
				scrollingStep = 3;
			}
		}
		initTopBar(savedInstanceState, R.layout.bu_tab_main);
		mReport = (ReportContainer) findViewById(R.id.report_tab);
		mReport.setHeighted(isHeighted);
		fillEmptyData();
		if (titles.size() - 1 > 3) {
			mReport.initShoreMore(true);
		}

		if (StringUtils.isEmpety(SelfApplication.getDataReadModel()) || "1".equals(SelfApplication.getDataReadModel())) {
			requestWSData(menuInfo.getMenu_id(), statDate);
		} else {
			new Thread(new Runnable() {

				@Override
				public void run() {
					List<String> rowsData = TableHolder.getValues(menuInfo.getMenu_id(), statDate);
					if (rowsData.size() < 1) {
						locHandler.sendEmptyMessage(REQUEST_WS_DATA);
					} else {
						locHandler.sendEmptyMessage(TABLE_INIT_START);
						for (String rowdata : rowsData) {
							List<SpannableString> row = new ArrayList<SpannableString>();
							for (String value : rowdata.split(TableHolder.Keys.COLUMN_SPLIT)) {
								row.add(processUpAndDownPic(new SpannableString(value), value));
							}
							Message msg = new Message();
							msg.what = ADD_ROW;
							msg.obj = row;
							locHandler.sendMessage(msg);
						}
						locHandler.sendEmptyMessage(TABLE_INIT_END);
					}
				}
			}).start();
		}

	}

	int ADD_ROW = 0x98;
	int REQUEST_WS_DATA = 0x99;
	int TABLE_INIT_START = 0x12;
	int TABLE_INIT_END = 0x13;
	ProgressDialog progressDialog;
	private Handler locHandler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == REQUEST_WS_DATA) {
				requestWSData(menuInfo.getMenu_id(), statDate);
			} else if (msg.what == TABLE_INIT_START) {
				progressDialog = ProgressDialog.show(TableList.this, "", "正在加载，请稍候...", true);
				progressDialog.setCancelable(true);
				mReport.resetReport();
			} else if (msg.what == ADD_ROW) {
				mReport.addReportItem((List<SpannableString>) msg.obj, scrollingStep, Rate.RATE_NONE, false);
			} else if (msg.what == TABLE_INIT_END) {
				topBar.setLogicBtnText(selectedDate);
				fillTable(mReport.getRowNum(), titles.size());
				progressDialog.dismiss();
			}
		}

	};

	private void requestWSData(String menuId, String statDate) {
		getWebServiceData(SelfApplication.getUserInfo().getTicket(), menuId, statDate, true, new DataInitListeren() {

			@Override
			public void initData(ProgressDialog progressDialog, boolean isShow) {
				progressDialog.dismiss();
			}
		});
	}

	@Override
	public void topBarLogic(TopBar topBar) {
		super.topBarLogic(topBar);
		this.topBar = topBar;

		initTopBarReturn(topBar);
		if (null != menuInfo) {
			topBar.setTitle(menuInfo.getMenu_name());
		}

		try {
			java.util.Date date = WheelDateDialog.SDF.parse(statDate);
			selectedDate = sdf_show.format(date);
			topBar.setLogicBtnText(selectedDate);
		} catch (ParseException e) {
			PopMsg.show("时间选择错误！");
		}

		topBar.setTopBarBtnListern(new TopBar.LogicBtnListern() {

			@Override
			public void onClickLogicBtn() {
				showDateTime(REQ_HITCH_TIME);
			}
		});
	}

	private void showDateTime(int requestCode) {
		WheelDateDialog dateTimeDialog = new WheelDateDialog(this, requestCode, statDate);
		dateTimeDialog.setDateChangeListener(new WheelDateDialog.DateChangeListener() {
			@Override
			public void onKeySave(int requestCode, String dateTimeValue) {
				if (REQ_HITCH_TIME == requestCode) {
					try {
						java.util.Date date = WheelDateDialog.SDF.parse(dateTimeValue);
						selectedDate = sdf_show.format(date);
						requestWSData(menuInfo.getMenu_id(), dateTimeValue);
					} catch (ParseException e) {
						PopMsg.show("时间选择错误！");
					}
				}
			}
		});
		dateTimeDialog.show();
	}

	private void fillEmptyData() {
		mReport.setTitleSize(ReportContainer.TITLE_SIZE_PS);
		mReport.initReportTitle(titles, false, this);
	}

	@Override
	protected void paser(SoapObject soapObject, final String statDate) {

		if (null != soapObject) {
			String stauts = soapObject.getPropertySafelyAsString("status");
			SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
			String message = msgObjec.getPropertySafelyAsString("message");
			if ("-2".equals(stauts)) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("-1".equals(stauts)) {
				Message msg = new Message();
				msg.what = TO_LOGIN;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("0".equals(stauts)) {
				SoapObject retMsgObject = (SoapObject) soapObject.getProperty("retMsg");

				Message msg = new Message();
				msg.what = UPDATE_LIST_UI;
				msg.obj = retMsgObject;
				Bundle data = new Bundle();
				data.putString("statDate", statDate);
				msg.setData(data);
				handler.sendMessage(msg);

			}
		}
	}

	private static final int UPDATE_LIST_UI = 0x101;
	private static final int ERROR_MSG = 0x1013;
	private static final int TO_LOGIN = 0x1019;
	private Handler handler = new Handler() {

		@SuppressLint("HandlerLeak")
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == UPDATE_LIST_UI) {
				if (null != msg.obj) {
					updateTableUI((SoapObject) msg.obj, msg.getData().getString("statDate"));
				}
			} else if (msg.what == ERROR_MSG) {
				PopMsg.show((String) msg.obj);
			} else if (msg.what == TO_LOGIN) {
				PopMsg.show((String) msg.obj);
				StartHelper.startActivity(Login.class);
				finish();
			}
		}

	};

	@SuppressLint("DefaultLocale")
	private void updateTableUI(SoapObject retMsgObject, String statDate) {
		int count = mReport.getRowNum();
		if (null != retMsgObject && retMsgObject.getPropertyCount() > 0) {
			mReport.resetReport();
			count = retMsgObject.getPropertyCount();
			StringBuilder allRowsData = new StringBuilder();
			for (int index = 0; index < count; index++) {
				allRowsData.append(TableHolder.Keys.ROW_SPLIT);
				SoapObject reportBeanObject = (SoapObject) retMsgObject.getProperty(index);
				List<SpannableString> row = new ArrayList<SpannableString>();
				SoapObject listValues = (SoapObject) reportBeanObject.getProperty("list");
				StringBuilder data = new StringBuilder();
				for (int tabIndex = 0; tabIndex < listValues.getPropertyCount(); tabIndex++) {
					data.append(TableHolder.Keys.COLUMN_SPLIT);
					String value = listValues.getPropertyAsString(tabIndex);
					if (null != value && "anyType{}".toLowerCase().equals(value.trim().toLowerCase())) {
						value = "";
					}
					data.append(value);
					row.add(processUpAndDownPic(new SpannableString(value), value));
				}
				allRowsData.append(data.deleteCharAt(0).toString());
				mReport.addReportItem(row, scrollingStep, Rate.RATE_NONE, false);
			}
			TableHolder.saveOrUpdate(menuInfo.getMenu_id(), statDate, allRowsData.deleteCharAt(0).toString());
			topBar.setLogicBtnText(selectedDate);
		} else {
			PopMsg.show("暂无  " + selectedDate + "  数据！", Toast.LENGTH_LONG);
		}
		fillTable(count, titles.size());
	}

	private void fillTable(int rowCount, int titles) {
		if (rowCount < CmccConfig.TABLE_ROWS) {
			for (int index = rowCount; index < CmccConfig.TABLE_ROWS; index++) {
				List<SpannableString> row = new ArrayList<SpannableString>();
				for (int tabIndex = 0; tabIndex < titles; tabIndex++) {
					row.add(new SpannableString(""));
				}
				mReport.addReportItem(row, scrollingStep, Rate.RATE_NONE, false);
			}
		}
	}

	private SpannableString processUpAndDownPic(SpannableString s_name, String value) {
		if (value.contains("D")) {
			Drawable down = getResources().getDrawable(R.drawable.arrow_down_green); // 用来替换的图像
			down.setBounds(0, 0, down.getIntrinsicWidth(), down.getIntrinsicHeight());
			ImageSpan span = new ImageSpan(down, ImageSpan.ALIGN_BASELINE);
			s_name.setSpan(span, value.indexOf("D"), value.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		} else if (value.contains("U")) {
			Drawable up = getResources().getDrawable(R.drawable.arrow_up_red); // 用来替换的图像
			up.setBounds(0, 0, up.getIntrinsicWidth(), up.getIntrinsicHeight());
			ImageSpan span = new ImageSpan(up, ImageSpan.ALIGN_BASELINE);
			s_name.setSpan(span, value.indexOf("U"), value.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		return s_name;
	}
}
